import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dbio_utils/fasta/indexed_fasta.dart';
import 'package:dbio_utils/generic_filehandle/generic_file_handle.dart';
import 'package:dbio_utils/generic_filehandle/local_file.dart';
import 'package:dbio_utils/gff/api.dart';
import 'package:dbio_utils/gff/gff.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:dbio_utils/gff/gff_parser.dart';

import 'dart:io';
import 'package:path/path.dart';

/// Build a file path.
String toFilePath(String parent, String path, {bool windows}) {
  var uri = Uri.parse(path);
  path = uri.toFilePath(windows: windows);
  if (isRelative(path)) {
    return normalize(join(parent, path));
  }
  return normalize(path);
}

void main() {
  final stuff = {
    'features': [],
    'comments': [],
    'directives': [],
    'sequences': [],
    'all': [],
  };

  _onData(d) {
    print(d);
    stuff['all'].add(d);
    if (d is DirectiveFeature)
      stuff['directives'].add(d);
    else if (d is CommentFeature)
      stuff['comments'].add(d);
    else if (d is GffFeature)
      stuff['features'].add(d);
    else
      stuff['sequences'].add(d);
  }

  parseAll(GenericFileHandle file) async {
    print('start parse: ${DateTime.now()}');
    Stream<BaseFeature> stream = parseFile(
      file,
      parseFeatures: true,
      parseDirectives: true,
      parseComments: true,
      parseSequences: true,
      bufferSize: 100,
    );
    var rst = await stream.toList();
    rst.forEach((e) => print(e));
    // print('parsed feature count: ${rst.length}');
    // print('start parse: ${DateTime.now()}');
    // stream.where((f) => f['ID'] == 'gene-Dmel_CR33449').listen((e) {
    //   print(e);
    // });

    // await for (var f in stream) {
    //   print(f);
    // }
    print('end parse: ${DateTime.now()}');

    // stream.listen(
    //   _onData,
    //   onDone: () {
    //     print('done');
    //   },
    // );
  }

  test('read parse gff', () async {
    LocalFile gff3_with_syncs = LocalFile(File('/Users/leeo/Downloads/gff3_with_syncs.gff3'));
    LocalFile gff3_ghl = LocalFile(File('/Users/leeo/Downloads/big_demo/ghl_demo_gff.gff'));
    LocalFile volvox = LocalFile(File('/Users/leeo/Downloads/BAM - volvox-sorted.bam-ctgA-1..50001.gff3'));
    LocalFile tomato = LocalFile(File('/Users/leeo/Downloads/tomato.gff3'));
    LocalFile human19 = LocalFile(File('/Users/leeo/Downloads/Ensembl Genes-chr1-1..249250621.gff3'));
    LocalFile fasta = LocalFile(File('/Users/leeo/Downloads/big_demo/ghl_demo_fasta.fasta'));
    await parseAll(human19);
    // await for (var line in human19.openStream().transform(utf8.decoder).transform(LineSplitter())) {
    //   print(line);
    // }
  });
}
